import asyncio
import sys
import os
from .base_client import BaseChatClient


class CLIClient(BaseChatClient):
    """命令行聊天客户端"""

    def __init__(self, config_file=None):
        super().__init__(config_file)
        self.users = []

    async def on_connected(self):
        """连接成功时调用"""
        print(f"成功连接到服务器 {self.server_address}")
        print(f"欢迎用户 {self.user_id} 加入房间 {self.room_id}")
        print("输入 '/help' 查看可用命令")
        print("=" * 50)

    async def on_disconnected(self):
        """断开连接时调用"""
        print("与服务器的连接已断开")

    async def on_text_message_received(self, formatted_message, sender, raw_message):
        """收到文本消息时调用"""
        print(formatted_message)

    async def on_file_received(self, file_data):
        """收到文件时调用"""
        sender = file_data['sender']
        filename = file_data['filename']
        filedata = file_data['filedata']
        timestamp = file_data['timestamp']

        print(f"[{timestamp}] 用户 {sender} 发送了一个文件: {filename}")

        # 询问是否保存文件
        save_choice = input(f"是否保存来自用户 {sender} 的文件 {filename}? (y/n): ")
        if save_choice.lower() == 'y':
            # 获取保存路径
            save_path = input(f"请输入保存路径 (默认: ./downloads/{filename}): ").strip()
            if not save_path:
                save_path = f"./downloads/{filename}"

            # 创建下载目录
            download_dir = os.path.dirname(save_path)
            if download_dir and not os.path.exists(download_dir):
                os.makedirs(download_dir, exist_ok=True)

            try:
                # 解码并保存文件
                import base64
                file_bytes = base64.b64decode(filedata)
                with open(save_path, "wb") as f:
                    f.write(file_bytes)
                print(f"文件已保存到: {save_path}")
            except Exception as e:
                print(f"保存文件失败: {str(e)}")
        else:
            print("文件接收已取消")

    async def on_system_message_received(self, formatted_message, raw_message):
        """收到系统消息时调用"""
        print(formatted_message)

    async def on_user_list_updated(self, users):
        """用户列表更新时调用"""
        self.users = users
        print(f"当前在线用户: {', '.join(users)}")

    async def on_message_sent(self, message):
        """消息发送成功时调用"""
        # 命令行客户端中通常不需要特殊处理发送成功的消息
        pass

    async def on_file_sent(self, filename):
        """文件发送成功时调用"""
        print(f"文件 {filename} 已发送")

    async def on_error(self, error_message):
        """发生错误时调用"""
        print(f"错误: {error_message}")

    def show_help(self):
        """显示帮助信息"""
        help_text = """
可用命令:
/help - 显示此帮助信息
/users - 显示当前在线用户
/sendfile - 发送文件
/exit - 退出程序
直接输入文字 - 发送文本消息
        """
        print(help_text)

    async def send_file_interactive(self):
        """交互式发送文件"""
        file_path = input("请输入要发送的文件路径: ").strip()
        if not file_path:
            print("文件路径不能为空")
            return

        if not os.path.exists(file_path):
            print("文件不存在")
            return

        await self.send_file(file_path)

    async def run(self):
        """运行客户端"""
        # 获取连接参数
        server_address_ = self.config.get("server_address", "ws://localhost:18229")
        server_address = input(f"服务器地址 (默认: {server_address_}): ").strip()
        if not server_address:
            server_address = server_address_

        user_id_ = self.config.get("user_id", f"user_{os.getpid()}")
        user_id = input(f"用户ID (默认: {user_id_}): ").strip()
        if not user_id:
            user_id = user_id_

        room_id_ = self.config.get("room_id", "default")
        room_id = input(f"房间ID (默认: {room_id_}): ").strip()
        if not room_id:
            room_id = room_id_

        # 连接到服务器
        await self.connect(server_address, user_id, room_id)

        # 主循环
        try:
            while self.is_connected:
                try:
                    message = await asyncio.get_event_loop().run_in_executor(None, input, "")
                    if message.startswith('/'):
                        command = message[1:].lower()
                        if command == 'help':
                            self.show_help()
                        elif command == 'users':
                            print(f"当前在线用户: {', '.join(self.users)}")
                        elif command == 'sendfile':
                            await self.send_file_interactive()
                        elif command == 'exit':
                            await self.disconnect()
                            break
                        else:
                            print("未知命令，输入 /help 查看可用命令")
                    elif message.strip():
                        await self.send_text_message(message)
                except EOFError:
                    # 用户按下 Ctrl+D
                    await self.disconnect()
                    break
        except KeyboardInterrupt:
            await self.disconnect()
        finally:
            print("客户端已退出")


if __name__ == "__main__":
    client = CLIClient("cfg.json")
    asyncio.run(client.run())